<template>
  <el-drawer v-model="drawerVisible" :z-index="1000" :destroy-on-close="true" size="450px" :title="`${drawerProps.title}用户`">
    <el-form
      ref="userFormRef"
      label-width="100px"
      label-suffix=" :"
      :rules="rules"
      :disabled="drawerProps.isView"
      :model="drawerProps.row"
      :hide-required-asterisk="drawerProps.isView"
      v-if="drawerProps.row"
    >
      <el-form-item label="登录用户名" prop="userAccount">
        <el-input v-model="drawerProps.row!.userAccount" placeholder="请填写登录用户名" clearable></el-input>
      </el-form-item>
      <el-form-item label="密码" prop="userPasswd" v-if="drawerProps.title === '新增'">
        <el-input
          v-model="drawerProps.row!.userPasswd"
          type="password"
          placeholder="请输入密码"
          clearable
          show-password
        ></el-input>
      </el-form-item>
      <el-form-item label="姓名" prop="userName">
        <el-input v-model="drawerProps.row!.userName" placeholder="请填写用户姓名" clearable></el-input>
      </el-form-item>
      <el-form-item label="用户类型" prop="userType">
        <el-select v-model="drawerProps.row!.userType" placeholder="请选择用户类型" clearable>
          <el-option v-for="item in userType" :key="item.value" :label="item.label" :value="item.value" />
        </el-select>
      </el-form-item>
      <el-form-item label="性别" prop="sex">
        <el-select v-model="drawerProps.row!.sex" placeholder="请选择性别" clearable>
          <el-option v-for="item in genderType" :key="item.value" :label="item.label" :value="item.value" />
        </el-select>
      </el-form-item>
      <el-form-item label="工号" prop="jobNumber">
        <el-input v-model="drawerProps.row!.jobNumber" placeholder="请填写工号" clearable></el-input>
      </el-form-item>
      <el-form-item label="工作单位" prop="company">
        <el-input v-model="drawerProps.row!.company" placeholder="请填写工作单位" clearable></el-input>
      </el-form-item>
      <el-form-item label="所属部门" prop="department">
        <el-input v-model="drawerProps.row!.department" placeholder="请填写所属部门" clearable></el-input>
      </el-form-item>
      <el-form-item label="联系方式" prop="mobile">
        <el-input v-model="drawerProps.row!.mobile" placeholder="请填写联系方式" clearable></el-input>
      </el-form-item>
      <el-form-item label="email" prop="email">
        <el-input v-model="drawerProps.row!.email" placeholder="请填写email" clearable></el-input>
      </el-form-item>
      <el-form-item label="用户头像">
        <el-upload
          class="avatar-uploader"
          :show-file-list="false"
          :on-change="uploadFile => _uploadFile(uploadFile)"
          :auto-upload="false"
        >
          <img
            v-if="drawerProps.row!.headFileId"
            :src="`${VITE_API_URL}/file/download/${drawerProps.row!.headFileId}`"
            class="avatar"
          />
          <el-icon v-else class="avatar-uploader-icon"><Plus /></el-icon>
        </el-upload>
      </el-form-item>
      <el-form-item label="状态" prop="status">
        <el-select v-model="drawerProps.row!.status" placeholder="请选择状态" clearable>
          <el-option v-for="item in status" :key="item.value" :label="item.label" :value="item.value" />
        </el-select>
      </el-form-item>
      <el-form-item label="角色" prop="roleList">
        <el-checkbox-group v-model="drawerProps.row!.roleList" placeholder="请选择角色" clearable>
          <el-checkbox v-for="(value, key) in roleList" :key="key" :label="value.roleId">
            {{ value.roleName }}
          </el-checkbox>
        </el-checkbox-group>
      </el-form-item>
    </el-form>
    <template #footer>
      <el-button @click="_colse">取消</el-button>
      <el-button type="primary" v-show="!drawerProps.isView" @click="handleSubmit">确定</el-button>
    </template>
  </el-drawer>
</template>

<script setup lang="ts" name="UserDrawer">
import { ref, reactive, onMounted } from "vue";
import { genderType, userType, status } from "@/utils/serviceDict";
import { ElMessage, FormInstance, UploadFile } from "element-plus";
import { User } from "@/api/interface";
import { getRoleTree } from "@/api/modules/user";

import { VITE_API_URL } from "@/config/index";
import { uploadFile } from "@/api/modules/common";
import { Plus } from "@element-plus/icons-vue";
const roleList: any = ref([]);
const rules = reactive({
  userAccount: [{ required: true, message: "请填写登录用户名" }],
  userPasswd: [
    { required: true, message: "请填写密码" },
    {
      pattern: /^((?=.*[a-zA-Z])(?=.*\d))*((?=.*[a-zA-Z])(?=.*[!@#$%^&*()_+]))*[a-zA-Z\d!@#$%^&*()_+]{6,18}$/,
      message: "密码6-18位(含数字、字母、特殊字符_-)",
      trigger: "blur"
    }
  ],
  userName: [{ required: true, message: "请填写姓名" }],
  userType: [{ required: true, message: "请选择用户类型" }],
  status: [{ required: true, message: "请选择状态" }],
  roleList: [{ required: true, message: "请选择角色" }],
  mobile: [
    {
      pattern: /(?:[-+() ]*\d){10,13}/gm,
      message: "联系方式格式不正确",
      trigger: "blur"
    }
  ],
  email: [
    {
      pattern: /\w+([-+.]\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*/,
      message: "emial格式不正确",
      trigger: "blur"
    }
  ]
});

interface DrawerProps {
  title: string;
  isView: boolean;
  row: Partial<User.ResUserList>;
  api?: (params: any) => Promise<any>;
  getTableList?: () => void;
  resetTableList?: () => void;
}

const drawerVisible = ref(false);
const drawerProps = ref<DrawerProps>({
  isView: false,
  title: "",
  row: {}
});

// 接收父组件传过来的参数
const acceptParams = (params: DrawerProps) => {
  drawerProps.value = params;
  drawerVisible.value = true;
  if (drawerProps.value.title === "新增") {
    drawerProps.value.row.userPasswd = "";
  }
  drawerProps.value.row.roleList = drawerProps.value.row?.roleList?.map(item => {
    return item.roleId;
  });
};

// 提交数据（新增/编辑）
const userFormRef = ref<FormInstance>();
/**
 * 关闭弹窗
 */
const _colse = () => {
  drawerVisible.value = false;
  userFormRef.value && userFormRef.value.resetFields();
};
/**
 * 提交信息
 */
const handleSubmit = () => {
  userFormRef.value!.validate(async valid => {
    if (!valid) return;
    drawerProps.value.row.roleList = drawerProps.value.row.roleList!.map(value => {
      return { roleId: value };
    });

    try {
      await drawerProps.value.api!(drawerProps.value.row);
      ElMessage.success({ message: `${drawerProps.value.title}用户成功！` });
      drawerProps.value.title === "新增" ? drawerProps.value.resetTableList!() : drawerProps.value.getTableList!();
      drawerVisible.value = false;
    } catch (error) {
      console.log(error);
    }
  });
};

/**
 * 文件上传
 */
const _uploadFile = (file: UploadFile) => {
  const site = file.name.lastIndexOf("\.");
  const fileName = file.name.substring(0, site);
  const fileSuffix = file.name.substring(site + 1, file.name.length);

  const imgTypelist = ["png", "jpg", "jpeg", "gif"];
  if (!imgTypelist.includes(fileSuffix)) {
    ElMessage.error("文件类型不匹配或不支持该种类型文件");
    return false;
  }
  filetoBase64(file.raw as File).then(async (base64Value: any) => {
    if (base64Value.indexOf("base64,") != -1) {
      base64Value = base64Value.substr(base64Value.indexOf("base64,") + 7);
    }
    try {
      const res = await uploadFile({
        fileType: "deviceDevOps",
        fileContent: base64Value,
        fileName,
        fileSuffix
      });
      drawerProps.value.row!.headFileId = res.fileId;
    } catch (error) {}
  });
};
const filetoBase64 = (file: File) => {
  let reader = new FileReader(); //实例化文件读取对象
  reader.readAsDataURL(file); //将文件读取为 DataURL,也就是base64编码
  return new Promise(reslove => {
    reader.onload = e => {
      //文件读取成功完成时触发
      if (e.target) {
        let dataURL = e.target.result; //获得文件读取成功后的DataURL,也就是base64编码
        reslove(dataURL);
      }
    };
  });
};
onMounted(async () => {
  const res = await getRoleTree();
  roleList.value = res.roleList;
});
defineExpose({
  acceptParams
});
</script>
<style scoped>
.avatar-uploader .avatar {
  display: block;
  width: 100px;
  height: 100px;
}
</style>

<style>
.avatar-uploader .el-upload {
  position: relative;
  overflow: hidden;
  cursor: pointer;
  border: 1px dashed var(--el-border-color);
  border-radius: 6px;
  transition: var(--el-transition-duration-fast);
}
.avatar-uploader .el-upload:hover {
  border-color: var(--el-color-primary);
}
.el-icon.avatar-uploader-icon {
  width: 100px;
  height: 100px;
  font-size: 28px;
  color: #8c939d;
  text-align: center;
}
</style>
